package cn.itcast.itcaststore.web.filter;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLEncoder;

@WebFilter(urlPatterns = { "/client/activesuccess.jsp","/client/cart.jsp","/client/createOrderSuccess.jsp",
        "/client/info.jsp",
        "/client/modifyuserinfo.jsp",
        "/client/order.jsp",
        "/client/orderInfo.jsp",
        "/client/orderlist.jsp",
        "/client/pay.jsp",
        "/client/paysuccess.jsp",
        "/client/product_list.jsp",
        "/client/product_list_2.jsp",
        "/client/product_search_list.jsp",
        "/client/myAccount.jsp",
})
public class CheckLoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest httpRequest = (HttpServletRequest)request;

        String dialogStr;	//弹出对话框的代码
        String message = URLEncoder.encode("您尚未登录，请登录再操作！！！", "utf-8");//弹出的提示消息
        String url="/client/login.jsp";			//重定向的链接地址

        String login = (String) httpRequest.getSession().getAttribute("login");
        if ("true".equals(login)){
            chain.doFilter(request, response);
        }else {
            dialogStr = "<script language ='javascript' charset=\"UTF-8\">\r\n\t";
            dialogStr +="message=decodeURI('"+message+"')\n";
            dialogStr +="alert(message);\r\n\t";			//弹出对话框
            dialogStr +="window.location.href = '"+url+"';\r\n";//页面重定向
            dialogStr += "</script>";

            response.getWriter().write(dialogStr);

        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
